import { useRoute } from 'vue-router';
import { useAuthStore } from '@/store/modules/auth';
import { fetchGetAllRoles, fetchGetRoleButtons, fetchGetRoleMenuButtons } from '@/service/api/system-manage';

export function useAuth() {
  const authStore = useAuthStore();

  // 缓存用户按钮权限，避免重复请求
  let cachedUserButtons: string[] | null = null;

  async function getUserButtonPermissions(): Promise<string[]> {
    // 如果已经缓存，直接返回
    if (cachedUserButtons !== null) {
      return cachedUserButtons;
    }

    try {
      const userRoles = authStore.userInfo.roles;
      // console.log('获取用户按钮权限，用户角色:', userRoles);

      if (!userRoles || userRoles.length === 0) {
        console.warn('用户没有角色信息，返回空按钮权限');
        cachedUserButtons = [];
        return [];
      }

      // 获取所有角色信息，用于角色code到ID的映射
      const allRolesResponse = await fetchGetAllRoles();
      if (!allRolesResponse.data || !Array.isArray(allRolesResponse.data)) {
        console.warn('获取所有角色信息失败，返回空按钮权限');
        cachedUserButtons = [];
        return [];
      }

      const roleCodeToIdMap = new Map<string, number>();
      allRolesResponse.data.forEach(role => {
        roleCodeToIdMap.set(role.roleCode, role.id);
      });
      // console.log('角色code到ID映射:', Object.fromEntries(roleCodeToIdMap));

      // 获取用户所有角色的按钮权限
      const allButtonCodes = new Set<string>();
      const roleButtonPromises = userRoles.map(async roleCode => {
        const roleId = roleCodeToIdMap.get(roleCode);
        if (!roleId) {
          console.warn(`未找到角色code ${roleCode} 对应的角色ID`);
          return;
        }

        // console.log(`获取角色 ${roleCode}(ID: ${roleId}) 的按钮权限...`);
        const roleButtonsResponse = await fetchGetRoleButtons(Number(roleId));
        if (roleButtonsResponse.data && Array.isArray(roleButtonsResponse.data)) {
          roleButtonsResponse.data.forEach(buttonCode => allButtonCodes.add(buttonCode));
          // console.log(`角色 ${roleCode} 的按钮权限:`, roleButtonsResponse.data);
        }
      });

      await Promise.all(roleButtonPromises);
      const userButtonCodes = Array.from(allButtonCodes);
      console.log('合并后的用户按钮权限:', userButtonCodes);

      // 缓存结果
      cachedUserButtons = userButtonCodes;
      return userButtonCodes;
    } catch (error) {
      console.warn('获取用户按钮权限失败，使用默认权限:', error);
      cachedUserButtons = [];
      return [];
    }
  }

  // 清除缓存，用于权限更新后刷新
  function clearButtonPermissionCache() {
    cachedUserButtons = null;
  }

  async function hasAuth(codes: string | string[]): Promise<boolean> {
    if (!authStore.isLogin) {
      return false;
    }

    const userButtons = await getUserButtonPermissions();

    if (typeof codes === 'string') {
      return userButtons.includes(codes);
    }

    return codes.some(code => userButtons.includes(code));
  }

  // 同步版本的权限检查，使用authStore中的buttons（如果可用）
  function hasAuthSync(codes: string | string[]): boolean {
    if (!authStore.isLogin) {
      return false;
    }

    const userButtons = authStore.userInfo.buttons;

    if (typeof codes === 'string') {
      return userButtons.includes(codes);
    }

    return codes.some(code => userButtons.includes(code));
  }

  // 基于菜单的按钮权限检查
  async function hasMenuButtonAuth(menuId: number, buttonCodes: string | string[]): Promise<boolean> {
    if (!authStore.isLogin) {
      return false;
    }

    const userRoles = authStore.userInfo.roles;
    if (!userRoles || userRoles.length === 0) {
      return false;
    }

    try {
      // 获取所有角色信息，用于角色code到ID的映射
      const allRolesResponse = await fetchGetAllRoles();
      if (!allRolesResponse.data || !Array.isArray(allRolesResponse.data)) {
        return false;
      }

      const roleCodeToIdMap = new Map<string, string>();
      allRolesResponse.data.forEach(role => {
        roleCodeToIdMap.set(role.roleCode, String(role.id));
      });

      // 检查用户所有角色在该菜单下的按钮权限
      const roleButtonPromises = userRoles.map(async roleCode => {
        const roleId = roleCodeToIdMap.get(roleCode);
        if (!roleId) return false;

        const response = await fetchGetRoleMenuButtons(Number(roleId), menuId);
        if (!response.data || !Array.isArray(response.data)) {
          return false;
        }

        const roleMenuButtons = response.data;

        if (typeof buttonCodes === 'string') {
          return roleMenuButtons.includes(buttonCodes);
        }

        return buttonCodes.some(code => roleMenuButtons.includes(code));
      });

      const results = await Promise.all(roleButtonPromises);
      return results.some(result => result);
    } catch (error) {
      console.error('检查菜单按钮权限失败:', error);
      return false;
    }
  }

  // 获取当前路由对应的菜单按钮权限
  async function hasCurrentMenuButtonAuth(buttonCodes: string | string[]): Promise<boolean> {
    const route = useRoute();
    const menuId = route.meta?.menuId as number;

    if (!menuId) {
      // 如果没有菜单ID，回退到全局按钮权限检查
      return hasAuth(buttonCodes);
    }

    return hasMenuButtonAuth(menuId, buttonCodes);
  }

  return {
    hasAuth,
    hasAuthSync,
    hasMenuButtonAuth,
    hasCurrentMenuButtonAuth,
    getUserButtonPermissions,
    clearButtonPermissionCache
  };
}
